import { Button, Form, Input, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState } from "react";
import { AtButton, AtFloatLayout, AtImagePicker } from "taro-ui";
import './index.less';

export const InfoBtn = (props: { setUserInfo: (info: any) => void }) => {
  const { setUserInfo } = props;
  const isWeapp = Taro.ENV_TYPE.WEAPP;
  const isAlipay = Taro.ENV_TYPE.ALIPAY;
  const [loading, setLoading] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [files, setFiles] = useState<any[]>([]);
  const [nickName, setNickName] = useState("");
  const [showImgAdd, setShowImgAdd] = useState(true);

  const onWechat = (e) => {
    setLoading(true);
    const { avatarUrl, nickName } = e.detail.userInfo || {};
    onLogin({avatar: avatarUrl, nickName}).then(() => {
      setLoading(false);
    });
  };

  const onAlipay = async () => {
    setLoading(true);
    try {
      const userInfo = await Taro.getOpenUserInfo({});
      const { avatarUrl, nickName } = JSON.parse(userInfo.response).response;
      await setUserInfo({ avatar: avatarUrl, nickName });
    } catch (err) {
      console.log(err);
    }
    setLoading(false);
  };

  const onFileChange = (files) => {
    if (files?.length) {
      setFiles(files);
    } else {
      setFiles([]);
    }
    setShowImgAdd(!files.length);
  };

  const onCloseLogin = () => {
    setShowImgAdd(true);
    setFiles([]);
    setNickName("");
    setShowLogin(false);
  };

  const onLogin = async(params: {avatar: string, nickName: string}) => {
    if (isWeapp) {
      const res = await Taro.cloud.callFunction({name: 'login', data: params});
      setUserInfo({...(res as any).result.data});
      Taro.atMessage({
        type: 'success',
        message: '恭喜您，登录成功！',
      })
      return res.result;
    }
  }

  const onFormSubmit = () => {
    if (!nickName) {
      Taro.atMessage({
        type: 'error',
        message: '您还有内容没有填写！',
      });
      return;
    }
    onLogin({avatar: files[0]?.url, nickName}).then(() => {
      onCloseLogin();
    });
  
  }

  return (
    <View>
      <Button
        openType={
          isWeapp ? "getUserInfo" : isAlipay ? "getAuthorize" : undefined
        }
        type="primary"
        loading={loading}
        onGetUserInfo={onWechat}
        onGetAuthorize={onAlipay}
        scope={isAlipay ? "userInfo" : undefined}
      >
        {isWeapp ? "微信登录" : isAlipay ? "支付宝登录" : "登录"}
      </Button>
      <Button style={{ marginTop: "10px" }} onClick={() => setShowLogin(true)}>普通登录</Button>

      <AtFloatLayout
        isOpened={showLogin}
        title="普通登录"
        onClose={onCloseLogin}
      >
        <View className="post-form">
          <Form
            onSubmit={onFormSubmit}
          >
            <View className="avatar-selector">
              <AtImagePicker
                length={1}
                mode="scaleToFill"
                count={1}
                files={files}
                showAddBtn={showImgAdd}
                onChange={onFileChange}
              />
            </View>
            <Input
              className="input-nickName"
              type="text"
              placeholder="点击输入昵称"
              value={nickName}
              onInput={(e) => setNickName(e.detail.value)}
            />
            <AtButton formType="submit" type="primary">
              登录
            </AtButton>
          </Form>
        </View>
      </AtFloatLayout>
    </View>
  );
};
